#!/usr/bin/python3
import Adafruit_SSD1306
import time
import subprocess

from ping3 import ping
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

OLED = Adafruit_SSD1306.SSD1306_128_64(
    rst=None, i2c_bus=1, gpio =1)  # 注意 使用的是哪组i2c的接口，对应调整i2c_bus取值

OLED.begin()  # 初始化屏幕并清屏
OLED.clear()
OLED.display()
time.sleep(1)

font = ImageFont.load_default()  # 设置字体为默认字体

width = OLED.width  # 设置屏幕长宽，并创建画布
height = OLED.height
image = Image.new("1", (width, height))
draw = ImageDraw.Draw(image)
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0, 0, width, height), outline=0, fill=0)

    # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk$
    cmd = "hostname -I | cut -d\' \' -f1"
    IP = subprocess.check_output(cmd, shell=True)
    cmd = "hostname -I | cut -d\' \' -f2"
    IP2 = subprocess.check_output(cmd, shell=True)
    cmd = "hostname -I | cut -d\' \' -f3"
    IP3 = subprocess.check_output(cmd, shell=True)
    # cmd = "hostname -I | cut -d\' \' -f4"
    # IP4 = subprocess.check_output(cmd, shell=True)

    cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
    CPU = subprocess.check_output(cmd, shell=True)
    cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell=True)
    cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
    Disk = subprocess.check_output(cmd, shell=True)

    cmd = "date|awk '{print $5}'"
    date = subprocess.check_output(cmd, shell=True)

    try:
        ping_delay = ping("www.baidu.com")
    except Exception as e:
        ping_delay = False

    if ping_delay:
        try:
            ping_result = 'Ping {0}ms'.format(int(1000*ping_delay))
        except Exception as e:
            ping_result = 'Ping failed'
    else:
        ping_result = 'Ping failed'


    draw.text((x, top),       str(IP).strip("\'\\nb"),  font=font, fill=255)
    draw.text((x, top+1*8),   str(IP2).strip("\'\\nb"),  font=font, fill=255)
    draw.text((x, top+2*8),   str(IP3).strip("\'\\nb"),  font=font, fill=255)
    # draw.text((x, top+3*8),   str(IP4).strip("\'\\nb"),  font=font, fill=255)
    draw.text((x, top+3*8),   str(CPU).strip("\'\\nb"), font=font, fill=255)
    draw.text((x, top+4*8),
              str(MemUsage).strip("\'\\nb"), font=font, fill=255)
    draw.text((x, top+5*8),   str(Disk).strip("\'\\nb"),  font=font, fill=255)
    draw.text((x, top+6*8),   str(date).strip("\'\\nb"),  font=font, fill=255)
    draw.text((x, top+7*8),   ping_result,  font=font, fill=255)

    # Display image.
    OLED.image(image)
    OLED.display()
    time.sleep(0.6)
